package xyz.xtt.schedule.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.lang.Assert;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.schedule.constants.ScheduleCacheConfig;
import xyz.xtt.schedule.entity.TblRegion;
import xyz.xtt.schedule.mapper.equity.TblRegionMapper;

/**
 * 行政区划服务
 *
 * @author dale
 * @since 2025/1/2
 **/
@Service
public class TblRegionService extends ServiceImpl<TblRegionMapper, TblRegion> {
	@Autowired
	private CacheManager cacheManager;

	/**
	 * 根据省市名称获取id
	 * 
	 * @param provinceName
	 * @param cityName
	 * @return
	 */
	public void ensureRegionDataExist(String provinceName, String cityName) {
		QueryWrapper queryWrapper = new QueryWrapper<TblRegion>().eq("region_name", provinceName).eq("parent_id", 0).eq("is_del", 0);
		Long provinceId = null;
		TblRegion province = cacheManager.cacheObj(() -> baseMapper.selectOne(queryWrapper), ScheduleCacheConfig.REGION_CACHE, getRegionKey(provinceName, 1));
		if (province == null) {
			provinceId = insertRegionData(provinceName, 0L, 1);
		} else {
			provinceId = province.getId();
		}

		Assert.notNull(provinceId);
		QueryWrapper cityQueryWrapper = new QueryWrapper<TblRegion>().eq("region_name", cityName).eq("parent_id", provinceId).eq("is_del", 0);
		TblRegion cityRegion = cacheManager.cacheObj(() -> baseMapper.selectOne(cityQueryWrapper), ScheduleCacheConfig.REGION_CACHE, getRegionKey(cityName, 2));
		if (cityRegion == null) {
			insertRegionData(cityName, provinceId, 2);
		}
	}

	/**
	 * 插入区划数据
	 * 
	 * @param regionName
	 * @param parentId
	 * @param level
	 * @return
	 */
	private Long insertRegionData(String regionName, long parentId, int level) {
		long now = System.currentTimeMillis();
		TblRegion region = TblRegion
				.builder()
				.regionName(regionName)
				.regionLevel(level)
				.parentId(parentId)
				.regionPinyin(lengthLimit(convertToPinyin(regionName), 100))
				.createTime(now)
				.updateTime(now)
				.isDel(false)
				.build();
		save(region);
		return region.getId();
	}

	/**
	 * 获取区划key
	 * 
	 * @param provinceName
	 * @param level
	 * @return
	 */
	private String getRegionKey(String provinceName, int level) {
		return provinceName + "_" + level;
	}

	/**
	 * 截取字符串
	 * 
	 * @param str
	 * @param maxLength
	 * @return
	 */
	private String lengthLimit(String str, Integer maxLength) {
		if (str != null && str.length() > maxLength) {
			return str.substring(0, maxLength);
		} else {
			return str;
		}
	}

	/**
	 * 将汉字转换为拼音
	 * 
	 * @param chineseText
	 * @return
	 */
	private String convertToPinyin(String chineseText) {
		StringBuilder pinyin = new StringBuilder();
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char c : chineseText.toCharArray()) {
			try {
				// 判断是否是汉字
				if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) {
					// 转换为拼音并取第一个结果
					String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
					if (pinyinArray != null) {
						pinyin.append(pinyinArray[0]);
					}
				} else {
					// 非汉字直接拼接
					pinyin.append(c);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return pinyin.toString().trim();
	}
}
